package com.example.csclient.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.csclient.model.CscModel
import com.example.csclient.ui.CscTopAppBar

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    modifier: Modifier = Modifier,
    cscUiState: CscUiState,
    appData: CscModel,
    onConfirmReservation: (TimePickerState, Boolean) -> Unit,
    onDismissReservation: () -> Unit,
    onConfirmHandModelAdjust: (handModelPercent: Float, powerAdjustPercent: Float) -> Unit,
    onConfirmRechargeMoney: (Float) -> Unit,
    onShowReservation: () -> Unit,
    onCancelReservation: () -> Unit,
    onOptionSelected: (String) -> Unit,
) {
    val timePickerState = rememberTimePickerState(0, 0, true)
    var willChargeAfterScheduleAttach by remember { mutableStateOf(false) }
    var handModelPercent by remember { mutableFloatStateOf(0.0f) }
    var powerAdjustPercent by remember { mutableFloatStateOf(0.0f) }

    if (cscUiState.showReservation) {
        ChargeReservationDialog(
            onConfirm = { onConfirmReservation(timePickerState, willChargeAfterScheduleAttach) },
            onDismiss = { onDismissReservation() }
        ) {
            Column {
                Text(
                    text = "设置预订时间",
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth().padding(bottom = 20.dp),
                    fontWeight = FontWeight.Bold,
                    fontSize = 20.sp
                )
                TimePicker(
                    state = timePickerState,
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
                HorizontalDivider()
                Row(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    if (willChargeAfterScheduleAttach) {
                        Text(
                            "预订到时后开始充电",
                            modifier = Modifier.weight(1f).align(Alignment.CenterVertically),
                            fontSize = 15.sp
                        )
                    } else {
                        Text(
                            "预订到时后停止充电",
                            modifier = Modifier.weight(1f).align(Alignment.CenterVertically),
                            fontSize = 15.sp
                        )
                    }
                    Switch(
                        checked = willChargeAfterScheduleAttach,
                        onCheckedChange = {
                            willChargeAfterScheduleAttach = it
                        }
                    )
                }
                HorizontalDivider()
            }
        }
    }

    if (cscUiState.showHandModelAdjust) {
        HandModelAdjust(
            onDismiss = {
                onConfirmHandModelAdjust(-1f, -1f)
            },
            onConfirm = {
                onConfirmHandModelAdjust(
                    handModelPercent * 0.35f + 0.6f,
                    powerAdjustPercent * 90_000.0f + 10_000.0f
                )
            }
        ) {
            Column {
                Text(
                    "拖动以调整恒压充电阈值",
                    modifier = Modifier.padding(bottom = 20.dp)
                )
                Slider(
                    value = handModelPercent,
                    onValueChange = { handModelPercent = it }
                )
                Text(
                    "%.1f %%".format(handModelPercent * 35 + 60),
                    textAlign = TextAlign.End,
                    modifier = Modifier.fillMaxWidth().padding(bottom = 20.dp)
                )

                HorizontalDivider()

                Text(
                    "拖动以调整最大充电功率大小",
                    modifier = Modifier.padding(vertical = 20.dp)
                )
                Slider(
                    value = powerAdjustPercent,
                    onValueChange = { powerAdjustPercent = it }
                )
                Text(
                    "%.1f kW".format(powerAdjustPercent * 90 + 10),
                    textAlign = TextAlign.End,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }

    if (cscUiState.showRechargeDialog) {
        var text by remember { mutableStateOf("") }
        var errorInfo by remember { mutableStateOf("") }
        var willShowErrorInfo by remember { mutableStateOf(false) }

        RechargeDialog(
            onConfirm = {
                try {
                    val rechargeMoney = text.toFloat()
                    if (rechargeMoney > 0.0f) {
                        onConfirmRechargeMoney(rechargeMoney)
                    } else {
                        errorInfo = "金额不可为负数"
                    }
                } catch (_: NumberFormatException) {
                    willShowErrorInfo = true
                    errorInfo = "请输入正确的数字"
                }
            }
        ) {
            Column {
                OutlinedTextField(
                    value = text,
                    onValueChange = {
                        text = it
                        willShowErrorInfo = false
                    },
                    label = { Text("请输入充值金额") }
                )
                if (willShowErrorInfo) {
                    Text(
                        text = errorInfo,
                        modifier = Modifier.padding(top = 10.dp)
                    )
                }
            }
        }
    }

    Column(
        modifier = modifier.padding(20.dp)
    ) {
        ChargeStateIndicator(cscUiState.chargeMode, appData.chargedTime)
        ChargeProgressIndicator(appData.chargePercent)

        //HorizontalDivider()
        ChargeModeSelection(cscUiState.selectedOption, onOptionSelected)

        HorizontalDivider()
        ChargeRecordIndicator(
            appData.chargePower,
            appData.chargeVoltage
        )

        HorizontalDivider()
        ChargeBalanceIndicator(
            appData.chargePrice,
            appData.chargeBalance,
            appData.chargeSurplusTime
        )

        HorizontalDivider()
        TemperatureIndicator(
            modifier = Modifier.padding(vertical = 20.dp),
            temperature = appData.chargeTemp
        )

        HorizontalDivider()
        ChargeReservationButton(
            Modifier.padding(top = 20.dp),
            buttonText =
                if (cscUiState.isInReservation)
                    appData.reservationTime
                else
                    "预订 / 手动模式调整",
            !cscUiState.isInReservation,
        ) { onShowReservation() }
        ChargeReservationButton(
            Modifier.padding(top = 10.dp),
            "取消预订",
            cscUiState.isInReservation,
        ) { onCancelReservation() }
    }
}


/**
 * 充电模式及已充电时间的展示
 */
@Composable
fun ChargeStateIndicator(
    chargeMode: String,
    chargingTime: String
) {
    Row(modifier = Modifier.padding(top = 10.dp, bottom = 5.dp)) {
        Text(chargeMode)
        Text(
            "已充电：${chargingTime}",
            modifier = Modifier.fillMaxWidth().align(Alignment.CenterVertically),
            textAlign = TextAlign.End
        )
    }
}

/**
 * 充电进度的指示，一个进度条和一个充电百分比
 */
@Composable
fun ChargeProgressIndicator(
    percent: Float
) {
    Row(modifier = Modifier.fillMaxWidth()) {
        LinearProgressIndicator(
            progress = { percent },
            modifier = Modifier.align(Alignment.CenterVertically).weight(1f)
        )
        Text(
            "${(percent * 100f).toInt()}%",
            textAlign = TextAlign.End,
            modifier = Modifier.padding(start = 10.dp)
        )
    }
}

/**
 * 充电模式选择按钮
 */
@Composable
fun ChargeModeSelection(
    selectedOption: String,
    onOptionSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val fastSlowOptions = listOf("快充模式", "慢充模式")
    val otherOptions = listOf("智能充电", "手动模式")

    // Note that Modifier.selectableGroup() is essential to ensure correct accessibility behavior
    Row {
        Column(
            modifier
                .selectableGroup()
                .weight(1f)
        ) {
            fastSlowOptions.forEach { text ->
                Row(
                    Modifier
                        .padding(vertical = 10.dp)
                        .selectable(
                            selected = (text == selectedOption),
                            onClick = { onOptionSelected(text) },
                            role = Role.RadioButton
                        )
                        .align(Alignment.CenterHorizontally),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = (text == selectedOption),
                        onClick = null // null recommended for accessibility with screen readers
                    )
                    Text(
                        text = text,
                        style = MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.padding(end = 5.dp)
                    )
                }
            }
        }
        Column(
            modifier
                .selectableGroup()
                .weight(1f)
        ) {
            otherOptions.forEach { text ->
                Row(
                    Modifier
                        .padding(vertical = 10.dp)
                        .selectable(
                            selected = (text == selectedOption),
                            onClick = { onOptionSelected(text) },
                            role = Role.RadioButton
                        )
                        .align(Alignment.CenterHorizontally),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    RadioButton(
                        selected = (text == selectedOption),
                        onClick = null // null recommended for accessibility with screen readers
                    )
                    Text(
                        text = text,
                        style = MaterialTheme.typography.bodyLarge,
                        modifier = Modifier.padding(end = 5.dp)
                    )
                }
            }
        }
    }
}

/**
 * 充电功率、充电电压指示器
 */
@Composable
fun ChargeRecordIndicator(
    chargePower: Float,
    chargeVoltage: Float
) {
    Row(
        Modifier.padding(vertical = 20.dp)
    ) {
        Column(
            Modifier.weight(1f)
        ) {
            Text(
                "充电功率",
                Modifier.align(Alignment.CenterHorizontally)
                    .padding(bottom = 8.dp),
                fontSize = 22.sp
            )
            if (chargePower > 1000.0f)
                Text(
                    //"${chargePower / 1000.0f}kW",
                    text = "%.1fkW".format(chargePower / 1000.0f),
                    Modifier.align(Alignment.CenterHorizontally),
                    fontSize = 30.sp,
                    fontWeight = FontWeight.Bold
                )
            else
                Text(
                    "${chargePower}W",
                    Modifier.align(Alignment.CenterHorizontally),
                    fontSize = 30.sp,
                    fontWeight = FontWeight.Bold
                )
        }
        Column(
            Modifier.weight(1f)
        ) {
            Text(
                "充电电压",
                Modifier.align(Alignment.CenterHorizontally)
                    .padding(bottom = 8.dp),
                fontSize = 22.sp
            )
            Text(
                "${chargeVoltage}V",
                Modifier.align(Alignment.CenterHorizontally),
                fontSize = 30.sp,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
fun ChargeBalanceIndicator(
    chargePrice: Float,
    chargeBalance: Float,
    chargeSurplusTime: String
) {
    Column(
        Modifier.padding(vertical = 20.dp)
    ) {
        Row {
            Text(
                "余额",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold
            )
            Text(
                "当前执行电价：¥%.2f / kWh".format(chargePrice),
                Modifier.fillMaxWidth().align(Alignment.CenterVertically),
                textAlign = TextAlign.End
            )
        }
        Row(
            Modifier.padding(top = 10.dp)
        ) {
            Text(
                "¥%.2f".format(chargeBalance),
                fontSize = 30.sp,
                fontWeight = FontWeight.Bold
            )
            Text(
                "预计充满时间：${chargeSurplusTime}",
                Modifier.fillMaxWidth().align(Alignment.CenterVertically),
                textAlign = TextAlign.End,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Composable
fun TemperatureIndicator(
    modifier: Modifier = Modifier,
    temperature: Float
) {
    Row(
        modifier = modifier
    ) {
        Text(
            text = "核心板温度：${temperature}℃",
            modifier = Modifier.weight(1f)
        )
        Text(
            text =
                if (temperature < 30.0f) {
                    "状态极好"
                } else if (temperature < 40.0f) {
                    "温度正常"
                } else if (temperature < 50.0f) {
                    "温度偏高"
                } else if (temperature < 60.0f) {
                    "警告：过热"
                } else {
                    "已开启过热保护"
                }
        )
    }
}

@Composable
fun ChargeReservationButton(
    modifier: Modifier = Modifier,
    buttonText: String,
    enabled: Boolean,
    onShowReservation: () -> Unit,
) {
    Button(
        modifier = modifier.fillMaxWidth(),
        onClick = { onShowReservation() },
        enabled = enabled
    ) {
        Text(buttonText)
    }
}

@Composable
fun HandModelAdjust(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        dismissButton = { },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@Composable
fun ChargeReservationDialog(
    onDismiss: () -> Unit = { },
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        dismissButton = {
            TextButton(onClick = { onDismiss() }) {
                Text("取消")
            }
        },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@Composable
fun RechargeDialog(
    onConfirm: () -> Unit,
    content: @Composable () -> Unit
) {
    AlertDialog(
        onDismissRequest = {  },
        confirmButton = {
            TextButton(onClick = { onConfirm() }) {
                Text("确定")
            }
        },
        text = { content() }
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun MainScreenPreview() {
    val uiState = CscUiState(
        loginState = true,
        showRechargeDialog = false
    )
    val appData = CscModel()

    Scaffold(
        topBar = {
            CscTopAppBar(
                cscUiState = uiState,
                onRechargeClicked = {},
                onStopClicked = {

                }
            )
        },
        modifier = Modifier.fillMaxSize()
    ) { innerPadding ->
        MainScreen(
            modifier = Modifier.padding(innerPadding),
            cscUiState = uiState,
            appData = appData,
            onConfirmReservation = { timePickerState, willChargeAfterScheduleAttach -> },
            onDismissReservation = {  },
            onConfirmHandModelAdjust = { handModelPercent, powerAdjustPercent -> },
            onCancelReservation = {  },
            onShowReservation = {  },
            onOptionSelected = { option -> },
            onConfirmRechargeMoney = { money -> }
        )
    }
}
